package com.yqg.education.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * Excel工具类
 */
public class ExcelUtil {
    protected static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
    private static final String SPLIT = ".";

    // 获取Excel表信息
    public static Workbook getWorkbook(MultipartFile file) {
        Workbook workbook = null;
        try {
            // 获取Excel后缀名
            String fileName = file.getOriginalFilename();
            if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(SPLIT) < 0) {
                logger.warn("解析Excel失败，因为获取到的Excel文件名非法！");
                return null;
            }
            String fileType = fileName.substring(fileName.lastIndexOf(SPLIT) + 1);
            // 获取Excel工作簿
            if (fileType.equalsIgnoreCase(XLS)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (fileType.equalsIgnoreCase(XLSX)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    // 获取Excel表头信息
    public static List<String> getSheetTitles(Workbook workbook) {
        // 拿第一个sheet表
        Sheet sheet = workbook.getSheetAt(0);
        // 校验sheet是否合法
        if (Objects.isNull(sheet)) {
            return null;
        }
        // 获取列名
        Row sheetTitleRow = sheet.getRow(2);
        // 取出最后一列
        short lastCellNum = sheetTitleRow.getLastCellNum();
        List<String> sheetTitleList = new LinkedList<>();
        for (int i = 0; i < lastCellNum; i++) {
            // 取出每一列的名
            String cellValue = sheetTitleRow.getCell(i).getStringCellValue();
            sheetTitleList.add(cellValue);
        }
        return sheetTitleList;
    }

}
